package cn.breeze.user.service.impl;

import cn.breeze.basic.constant.BaseConstants;
import cn.breeze.basic.exception.BusinessException;
import cn.breeze.basic.utils.MD5Utils;
import cn.breeze.basic.utils.StrUtils;
import cn.breeze.basic.vo.RegisterVo;
import cn.breeze.org.domain.Employee;
import cn.breeze.user.domain.Logininfo;
import cn.breeze.user.domain.User;
import cn.breeze.user.mapper.LogininfoMapper;
import cn.breeze.user.mapper.UserMapper;
import cn.breeze.user.service.IUserService;
import cn.breeze.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author breeze
 * @since 2022-07-05
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private IUserService iUserService;
    
    @Autowired
    private LogininfoMapper logininfoMapper;

    /**
    * @Title: phoneRegister
    * @Description: 用户手机号注册
    * @Author: Mr.D
    * @Version: 1.0
    * @Date:  2022/7/6 11:58
    * @Parameters: [registerVo]
    * @Return void
    */
    @Override
    public void phoneRegister(RegisterVo registerVo) {
        // 电话
        String phone = registerVo.getPhone();
        // 手机验证码
        String smsCodeValue = registerVo.getSmsCodeValue();
        // 密码
        String password = registerVo.getPassword();
        // 确认密码
        String confirmPassword = registerVo.getConfirmPassword();
        if (phone == null){
            throw new BusinessException("手机号不能为空！");
        }
        if (smsCodeValue == null){
            throw new BusinessException("验证码不能为空！");
        }
        if (password == null){
            throw new BusinessException("密码不能为空！");
        }
        // 验证两次输入的密码是否一致
        if (confirmPassword == null || !password.equals(confirmPassword)){
            throw new BusinessException("两次输入的密码不一致！");
        }
        // 根据用户号+中间键去redis中查询手机验证码
        Object smsCodeValueTmp = redisTemplate.opsForValue().get(BaseConstants.VerifyCodeConstant.BUSINESS_REGISTER_PREFIX + phone);
        // 验证用户输入的验证码是否正确
        if (smsCodeValueTmp == null){
            throw new BusinessException("验证码已失效，请重新获取！");
        }
        if (!smsCodeValue.equalsIgnoreCase(smsCodeValueTmp.toString().split(":")[0])){
            throw new BusinessException("验证码错误，请重新输入！");
        }
        // 根据电话查询user信息
        User userTmp = userMapper.loadByPhone(phone);
        // 判断当前号码是否已被注册
        if (userTmp != null){
            throw new BusinessException("当前号码已被注册，请直接登录！");
        }
        // 将registerVo设置到user对象
        userTmp = registerVo2User(registerVo);
        // 保存user信息
        userMapper.save(userTmp);
        // 将user设置到Logininfo
        Logininfo logininfo = User2LoginInfo(userTmp);
        // 保存logininfo信息
        logininfoMapper.save(logininfo);
        // 设置logininfo_id字段值
        userTmp.setLogininfoId(logininfo.getId());
        // 修改user信息
        userMapper.update(userTmp);
    }

    /** 
    * @Title: emailRegister
    * @Description: 邮箱注册
    * @Author: Mr.D
    * @Version: 1.0
    * @Date:  2022/7/7 18:24  
    * @Parameters: [registerVo]
    * @Return void
    */
    @Override
    public void emailRegister(RegisterVo registerVo) {
        // 邮箱
        String email = registerVo.getEmail();
        // 邮箱验证码
        String smsCodeValue = registerVo.getSmsCodeValue();
        // 密码
        String password = registerVo.getPassword();
        // 确认密码
        String confirmPassword = registerVo.getConfirmPassword();
        if (email == null){
            throw new BusinessException("邮箱不能为空！");
        }
        if (smsCodeValue == null){
            throw new BusinessException("验证码不能为空！");
        }
        if (password == null){
            throw new BusinessException("密码不能为空！");
        }
        // 验证两次输入的密码是否一致
        if (confirmPassword == null || !password.equals(confirmPassword)){
            throw new BusinessException("两次输入的密码不一致！");
        }
        // 根据用户号+中间键去redis中查询手机验证码
        Object smsCodeValueTmp = redisTemplate.opsForValue().get(BaseConstants.VerifyCodeConstant.BUSINESS_REGISTER_PREFIX + email);
        // 验证用户输入的验证码是否正确
        if (smsCodeValueTmp == null){
            throw new BusinessException("验证码已失效，请重新获取！");
        }
        if (!smsCodeValue.equalsIgnoreCase(smsCodeValueTmp.toString().split(":")[0])){
            throw new BusinessException("验证码错误，请重新输入！");
        }
        // 根据邮箱查询user信息
        User userTmp = userMapper.loadByPhone(email);
        // 判断当前号码是否已被注册
        if (userTmp != null){
            throw new BusinessException("当前号码已被注册，请直接登录！");
        }
        // 将registerVo设置到user对象
        userTmp = registerVo2User(registerVo);
        // 保存user信息
        userMapper.save(userTmp);
        // 将user设置到Logininfo
        Logininfo logininfo = User2LoginInfo(userTmp);
        // 保存logininfo信息
        logininfoMapper.save(logininfo);
        // 设置logininfo_id字段值
        userTmp.setLogininfoId(logininfo.getId());
        // 修改user信息
        userMapper.update(userTmp);
    }

    // 根据logininfoId查询
    @Override
    public User loadByLogininfoId(Long id) {
        return userMapper.loadByLogininfoId(id);
    }

    /** 
    * @Title: registerVo2User
    * @Description: 设置user对象数据
    * @Author: Mr.D
    * @Version: 1.0
    * @Date:  2022/7/6 12:45  
    * @Parameters: [registerVo]
    * @Return cn.breeze.user.domain.User
    */
    public User registerVo2User(RegisterVo registerVo){
        User user = new User();
        // 设置电话
        user.setPhone(registerVo.getPhone());
        // 设置邮箱
        user.setEmail(registerVo.getEmail());
        if (registerVo.getPhone() != null){
            // 设置用户名
            user.setUsername(registerVo.getPhone());
        } else {
            // 设置用户名
            user.setUsername(registerVo.getEmail());
        }
        // 获取盐值
        String salt = StrUtils.getComplexRandomString(32);
        // 根据验证和用户输入的密码进行md5加密
        String passwordMd5 = MD5Utils.encrypByMd5(salt + registerVo.getPassword());
        // 设置密码
        user.setPassword(passwordMd5);
        // 设置盐值
        user.setSalt(salt);
        return user;
    }

    /**
    * @Title: User2LoginInfo
    * @Description: 设置Logininfo对象信息
    * @Author: Mr.D
    * @Version: 1.0
    * @Date:  2022/7/6 12:51
    * @Parameters: [user]
    * @Return cn.breeze.user.domain.Logininfo
    */
    public Logininfo User2LoginInfo(User user){
        Logininfo logininfo = new Logininfo();
        // 将user对象拷贝到logininfo中
        BeanUtils.copyProperties(user,logininfo);
        // 设置type字段默认为1，用户
        logininfo.setType(1);
        return logininfo;
    }

    @Override
    public void save(User user) {
        // 初始化user
        initUser(user);
        // 保存user
        userMapper.save(user);
        // 初始化Logininfo
        Logininfo logininfo = User2LoginInfo(user);
        // 保存logininfo
        logininfoMapper.save(logininfo);
        // 设置user标的logininfoId
        user.setLogininfoId(logininfo.getId());
        // 修改user
        userMapper.update(user);
    }

    /** 
    * @Title: initUser
    * @Description: 初始化user
    * @Author: Mr.D
    * @Version: 1.0
    * @Date:  2022/7/6 18:25  
    * @Parameters: [user]
    * @Return void
    */
    private void initUser(User user) {
        String password = user.getPassword();
        // 获取盐值
        String salt = StrUtils.getComplexRandomString(32);
        // 根据盐值和密码md5加密
        String saltPassword = MD5Utils.encrypByMd5(salt + password);
        // 设置盐值
        user.setSalt(salt);
        // 设置密码
        user.setPassword(saltPassword);
    }

    @Override
    public void update(User user) {
        // 初始化user
        initUser(user);
        // 修改user
        userMapper.update(user);
        // 初始化Logininfo
        Logininfo logininfo = User2LoginInfo(user);
        // 设置logininfo的主键id
        logininfo.setId(user.getLogininfoId());
        // 修改logininfo
        logininfoMapper.update(logininfo);
    }

    @Override
    public void remove(Long id) {
        // 根据id获取用户信息
        User user = userMapper.loadById(id);
        // 删除用户信息
        userMapper.remove(id);
        // 删除对应的Logininfo表的登录信息
        logininfoMapper.remove(user.getLogininfoId());
    }
}
